package com.meitianhui.convenitenbuy.module.order.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jakewharton.rxbinding.view.RxView;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.AdWebViewActivity;
import com.meitianhui.convenitenbuy.module.order.model.bean.OrderInfo;
import com.meitianhui.convenitenbuy.module.order.ui.fragment.EdinburghOrderTypeFragment;
import com.meitianhui.convenitenbuy.util.DateUtil;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/13.
 */

public class EdinburghOrderAdapter extends BaseQuickAdapter<OrderInfo.ListBean, BaseViewHolder> {
    private Context mContext;
    private Map<String, String> mUrlMap;
    private OnClickOrder mOnClickOrder;
    private HashMap<String, CountDownTimer> countDownMap;
    private String status;
    public EdinburghOrderAdapter(Context context, List<OrderInfo.ListBean> data, Map<String, String> urlMap, OnClickOrder onClickOrder) {
        super(R.layout.item_edinburgh_order, data);
        mContext = context;
        mUrlMap = urlMap;
        mOnClickOrder = onClickOrder;
        countDownMap = new HashMap<String, CountDownTimer>();
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }

        for (CountDownTimer timer : countDownMap.values())
            if (timer != null) {
                timer.cancel();
            }
        }
    @Override
    protected void convert(BaseViewHolder helper, OrderInfo.ListBean item) {

        ImageView ivGood = helper.getView(R.id.iv_good);
        LinearLayout llAddress = helper.getView(R.id.ll_address);
        LinearLayout llRelationOrder = helper.getView(R.id.ll_relation_order);
        LinearLayout llRemark = helper.getView(R.id.ll_remark);
        LinearLayout btnConfirmOrder = helper.getView(R.id.ll_confirm_order);   //确认订单
        Button btnCancelOrder = helper.getView(R.id.btn_cancel_order);  //取消订单
        Button btnLogistics = helper.getView(R.id.btn_logistics);  //物流
        Button btnCustomer = helper.getView(R.id.btn_customer);  //联系客服
        LinearLayout llPrompt = helper.getView(R.id.ll_prompt);  //提示
        RelativeLayout rlPayment = helper.getView(R.id.rl_payment);  //前去付款
        RelativeLayout rlBig = helper.getView(R.id.rl_big_layout);  //下面按钮的大布局
        TextView tvMin = helper.getView(R.id.tv_min);  //分钟
        TextView tvSecond = helper.getView(R.id.tv_sec);  //秒钟
        helper.setText(R.id.tv_good_name, item.getItem_goods_title());   //商品标题
        helper.setText(R.id.tv_good_price, "预付金额: ¥" + item.getSale_fee() + " (返¥" + item.getTotal_fee() + ")");  //价格
        helper.setText(R.id.tv_order_number, item.getOrder_no());  //订单号
        helper.setText(R.id.tv_create_date, item.getOrder_date());  //时间
        helper.setText(R.id.tv_contact_person, item.getContact_person());  //联系人
        rlPayment.setVisibility(View.GONE);
        helper.setIsRecyclable(false);
        String path_id = "";
        try {
            JSONArray jsonArray = new JSONArray(item.getItem_goods_pic_info());
            path_id = jsonArray.getJSONObject(0).getString("path_id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        GlideUtils.setCircleImage(mContext,mUrlMap.get(path_id), R.mipmap.wallet_coupon_item_default, R.mipmap.wallet_coupon_item_default, ivGood);
        //配送地址
        String location = item.getDelivery_address();
        if (TextUtils.isEmpty(location)) {
            llAddress.setVisibility(View.GONE);
        } else {
            llAddress.setVisibility(View.VISIBLE);
            helper.setText(R.id.tv_address, location);
        }
        helper.setText(R.id.tv_address_phone, item.getContact_tel());
        //备注
        String remark = item.getRemark();
        if (!TextUtils.isEmpty(remark)) {
            llRemark.setVisibility(View.VISIBLE);
            helper.setText(R.id.tv_remark, remark);
        } else {
            llRemark.setVisibility(View.GONE);
        }
        status = item.getStatus();
        RxView.visibility(helper.getView(R.id.ll_return_time)).call(false);
        //订单的状态
        if (!TextUtils.isEmpty(status)) {
            if (status.equals(Constants.PC__ORDER_PROCESSING)) {    /**处理中**/
                btnCancelOrder.setVisibility(View.VISIBLE);
                btnLogistics.setVisibility(View.GONE);
                btnCustomer.setVisibility(View.GONE);
                rlPayment.setVisibility(View.VISIBLE);
                llPrompt.setVisibility(View.VISIBLE);
//                if ("meitianhui".equals(item.getOrder_type())) {
//                    btnConfirmOrder.setVisibility(View.GONE);
//                } else {
//                    btnConfirmOrder.setVisibility(View.VISIBLE);
//                }
                helper.setText(R.id.tv_status, "已预定");
                //取消订单
                btnCancelOrder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnClickOrder.cancelClick(item.getOrder_id());
                    }
                });
                //确认订单
                btnConfirmOrder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnClickOrder.confirmClick(item.getOrder_id());
                    }
                });
                rlBig.setVisibility(View.VISIBLE);
                rlPayment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        createDialog(item.getItem_taobao_link(),item.getOrder_id(),item.product_source);
                    }
                });
            } else if (status.equals(Constants.PC__ORDER_CONFIRMED)) {
                //已下单(48小时)
                helper.setText(R.id.tv_status, "已下单");
                btnCancelOrder.setVisibility(View.GONE);
                btnConfirmOrder.setVisibility(View.GONE);
                btnLogistics.setVisibility(View.GONE);
                btnCustomer.setVisibility(View.GONE);
                helper.setVisible(R.id.tv_return_time, true);
                String orderdate = item.getOrder_date();
                String s_date = DateUtil.getDistanceToNow(orderdate);
                if ("timeout".equals(s_date)) {
                    rlBig.setVisibility(View.VISIBLE);
                    helper.setText(R.id.tv_return_time, "如2个工作日未到账，请点击下方按钮联系客服");
                    btnCustomer.setVisibility(View.VISIBLE);
                    btnCustomer.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mOnClickOrder.customerClick();
                        }
                    });
                } else {
                    rlBig.setVisibility(View.GONE);
                    helper.setText(R.id.tv_return_time, "差额部分将于2个工作日内返还到您的账户");
                    btnCustomer.setVisibility(View.GONE);
                }
                RxView.visibility(helper.getView(R.id.ll_return_time)).call(true);
            } else if (status.equals(Constants.PC_ORDER_DELIVERED)) {
                helper.setText(R.id.tv_status, "已发货");
                rlBig.setVisibility(View.GONE);

            } else if (status.equals(Constants.PC__ORDER_PAYED)) {
                helper.setText(R.id.tv_status, "已支付");
                rlBig.setVisibility(View.GONE);
            } else if (status.equals(Constants.PC__ORDER_RECEIVED)) {
                helper.setText(R.id.tv_status, "已收货");
                rlBig.setVisibility(View.GONE);
            } else if (status.equals(Constants.PC__ORDER_CLOSED)) {
                helper.setText(R.id.tv_status, "已返款");
                //展示物流信息
                String logistics = item.getLogistics();
                if (!TextUtils.isEmpty(logistics)) {
                    try {
                        JSONObject jsonObject = new JSONObject(logistics);
                        String company = jsonObject.getString("company");
                        String number = jsonObject.getString("number");
                        if (!TextUtils.isEmpty(company) && !TextUtils.isEmpty(number)) {
                            rlBig.setVisibility(View.VISIBLE);
                            btnCustomer.setVisibility(View.GONE);
                            btnCancelOrder.setVisibility(View.GONE);
                            btnConfirmOrder.setVisibility(View.GONE);
                            btnLogistics.setVisibility(View.VISIBLE);
                            btnLogistics.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(mContext, AdWebViewActivity.class);
                                    intent.putExtra("url", Constants.HOST + "h5/c/payback/logistics"
                                            + "?order_id=" + item.getOrder_id());
                                    intent.putExtra("title", "查看物流");
                                    mContext.startActivity(intent);
                                }

                            });
                        } else {
                            rlBig.setVisibility(View.GONE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    rlBig.setVisibility(View.GONE);
                }
            } else if (status.equals(Constants.PC__ORDER_CANCELLED)) {
                helper.setText(R.id.tv_status, "已取消");
                rlBig.setVisibility(View.GONE);
            } else {
                helper.setText(R.id.tv_status, "未知");
                rlBig.setVisibility(View.GONE);
            }
        }
        //关联订单
        String relationOrder = item.getExternal_order_no();
        if (!TextUtils.isEmpty(relationOrder) && !"meitianhui".equals(item.getOrder_type())) {
            llRelationOrder.setVisibility(View.VISIBLE);
            helper.setText(R.id.tv_relation_order, relationOrder);
        } else {
            llRelationOrder.setVisibility(View.GONE);
        }

        if (item.systemTime == null) item.systemTime = System.currentTimeMillis();
        long time = Long.valueOf(item.diff_time) - (System.currentTimeMillis() - item.systemTime);
        //将前一个缓存
        CountDownTimer countDownTimer;

        countDownTimer = countDownMap.get(item.diff_time);
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (time > 0) {
            countDownTimer = new CountDownTimer(time, 1000) {
                public void onTick(long millisUntilFinished) {
                    leftTime(tvMin, tvSecond, (int) millisUntilFinished / 1000);
                }

                public void onFinish() {
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_ORDER_OPERATION));
                }
            }.start();
            countDownMap.put(item.diff_time, countDownTimer);
        }

    }

    private Dialog dialog;
    private void createDialog(final String taoBaoLink,final String orderId,final String productSource) {
        LinearLayout linearLayout  = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.dialog_goto_pay, null);
        TextView tvCancel  = (TextView) linearLayout.findViewById(R.id.cancel);
        ((TextView) linearLayout.findViewById(R.id.order_tips2)).setText(Html.fromHtml(mContext.getString(R.string.goto_pay)));
        TextView tvSubmit  = (TextView) linearLayout.findViewById(R.id.submit);
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        builder.setView(linearLayout);
        dialog  = builder.show();
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(taoBaoLink)) {
                    Map<String, String> exParams = new HashMap<>();
                    exParams.put("isv_code",orderId);
                    AlibcTrade.show( (Activity)mContext, new AlibcPage(taoBaoLink),
                            new AlibcShowParams(OpenType.Native, false),
                            null, exParams , new AlibcTradeCallback() {
                                @Override
                                public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

                                }
                                @Override
                                public void onFailure(int i, String s) {

                                }
                            });
                    try {
                        if (!SystemUtils.isAppInstalled(mContext, "com.taobao.taobao")) {
                            TipUtils.showToast(App.getInstance(),"没有检测到淘宝软件,打开失败", 2);
                        }
                    }catch ( Exception  e){
                        e.printStackTrace();
                    }
                    EdinburghOrderTypeFragment.isTaoBaoGoReFlesh = 2;
                    LogUtils.d("111",status);
                }else{
                    SystemUtils.open(App.getInstance(),productSource);
                }
                dialog.dismiss();
            }
        });
    }
    /**
     * 剩余的支付时间
     * @param tvMin
     * @param tvSecond
     * @param diffTime
     */
    private void leftTime(TextView tvMin, TextView tvSecond, int diffTime) {
        if (diffTime <= 0) {
            tvMin.setText("00");
            tvSecond.setText("00");
        } else {
            long min = ((diffTime / (60)));
            long s = (diffTime - min * 60);
            String s_min = min + "";
            if (s_min.length() == 1) {
                s_min = "0" + s_min;
            }
            String s_s = s + "";
            if (s_s.length() == 1) {
                s_s = "0" + s_s;
            }
            tvMin.setText(s_min);
            tvSecond.setText(s_s);
        }
    }

    public void setNewData(List data, Map<String, String> map) {
        setNewData(data);
        this.mUrlMap = map;
    }

    public void addData(List data, Map<String, String> map) {
        addData(data);
        mUrlMap.putAll(map);
    }

    public interface OnClickOrder {
        void cancelClick(String orderId);

        void confirmClick(String orderId);

        void customerClick();
    }

}
